package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.CirclePictureAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: UploadingActivity
 * @Description: 上传照片
 * @Author: ljp
 * @CreateDate: 2018/11/18 15:03
 * @Version: 1.0
 */
public class UploadingActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.recycler_send_pictuer)
    RecyclerView recyclerSendPictuer;
    //选择图片list
    private List<LocalMedia> tlist;
    private CirclePictureAdapter circlePictureAdapter;
    private List<LocalMedia> selectList;
    private String TAG = "UploadingActivity";
    private List<String> lists;
    private MySelfInfoBean.ObjectBean mySeleInfo;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_uploading;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        initView();
    }

    private void initView() {
        tlist = new ArrayList<>();
        circlePictureAdapter = new CirclePictureAdapter(context, tlist, R.layout.item_send_post_picture, 1);
        //FullyGridLayoutManager fullyGridLayoutManager = new FullyGridLayoutManager(context, 3);
       // fullyGridLayoutManager.setSmoothScrollbarEnabled(false);
        recyclerSendPictuer.setLayoutManager(new GridLayoutManager(activity,3));
        recyclerSendPictuer.setAdapter(circlePictureAdapter);
        circlePictureAdapter.addFooterView(R.layout.item_send_post_picture);
        circlePictureAdapter.setAddClick(new CirclePictureAdapter.OnAddClick() {
            @Override
            public void setAddItemClick(int position) {
                initPicture();
            }

            @Override
            public void setRemoveItemClick(int position) {
                tlist.remove(position);
                circlePictureAdapter.refreshCurrentAdapter();
            }

            @Override
            public void setSendImgBg(boolean flag) {
            }
        });
    }
    /**
    * @method
    * @description 上传照片到oss
    * @date: 2018/11/18 17:08
    * @author: ljp
    * @return
    */
    private void setOssHttp(List<String> list) {
        lists = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OssClient.getInstance().init(context).
                            ossUploads(list, new OssClient.OnUploadFile() {
                                @Override
                                public void onUploadFileSuccess(String info) {
                                    //Log.i(TAG, "onUploadFileSuccess: -----" + info);
                                    uploadHttp(info);
                                }
                                @Override
                                public void onUploadFileFailed(String errCode) {
                                }
                            },new StringBuffer());
                } catch (ClientException e) {
                    e.printStackTrace();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
    * @method
    * @description 上传图片地址到服务器
    * @date: 2018/11/18 16:40
    * @author: ljp
    * @return
    */
    private void uploadHttp(String path) {
        MeInfoService.uploadingPicture(mySeleInfo.getId(),SPUtils.getEditoString(SPUtils.SP_TOKEN), PhoneUtils.getDeviceInfo(context),path).subscribe(result -> {
            //Log.i(TAG, "uploadHttp: -----"+result.toString());
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
               Intent intent = new Intent(activity, PhotoAlbumActivity.class);
                intent.putExtra("anchorId",mySeleInfo.getId());
                startActivity(intent);
                finish();
            }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                tvSend.setEnabled(true);
                Utils.setToken(context);
            }else {
                tvSend.setEnabled(true);
                toast_MakeText(result.getMsg());
            }
        },throwable -> {
            tvSend.setEnabled(true);
            toast_MakeText(getResources().getString(R.string.net_error));
            //Log.i(TAG, "uploadHttp: ------"+throwable.toString());
        });

    }

    /**
     * @return
     * @method
     * @description 选择照片
     * @date: 2018/11/18 15:08
     * @author: ljp
     */
    private void initPicture() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(9)// 最大图片选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .compress(true)
                //.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //.isGif(true)// 是否显示gif图片 true or false
                .selectionMedia(tlist)// 是否传入已选图片 List<LocalMedia> list

                 /*.freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
                 .openClickSound()// 是否开启点击声音 true or false
                 .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false*/
                 .cropCompressQuality(90)// 裁剪压缩质量 默认90 int*/
                .minimumCompressSize(1024)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    //Log.i(TAG, "onActivityResult: -----" + selectList.size());
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // tlist.clear();
                    //tlist.addAll(selectList);
                    circlePictureAdapter.setList(selectList);
                    circlePictureAdapter.refreshCurrentAdapter();
                    break;
            }
        }
    }

    @OnClick({R.id.linear_back, R.id.tv_send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.tv_send://发布图片
                tvSend.setEnabled(false);
                setPictureList();
                break;
        }
    }

    private void setPictureList(){
        List<LocalMedia> tlist = circlePictureAdapter.getTlist();
        List<String> list = new ArrayList<>();
        for (int i = 0;i< tlist.size();i++){
            LocalMedia localMedia = tlist.get(i);
            list.add(localMedia.getCompressPath());
        }
        setOssHttp(list);
    }
}
